/*
 * @Descripttion: 组件业务名
 * @version:
 * @Author: lhl
 * @Date: 2024-10-25 14:13:40
 * @LastEditors: lhl
 * @LastEditTime: 2024-10-25 16:20:20
 */
import React from 'react';
import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import { useRoutes } from '@/hooks/useRoutes';
import { staticRoutes } from './StaticRoutes';
import Layout from '@/layout/Index';
import Login from '@/views/login/Login';
import NotFound from '@/views/notFound/404';
import PermissionButton from '@/components/PermissionButton';

const Router: React.FC = () => {
  const { isAuthenticated } = useAuth();
  const dynamicRoutes = useRoutes();

   // 添加日志来检查动态路由是否正确加载
   console.log('Dynamic routes:', dynamicRoutes);

  const renderRoutes = (routes: any[]) => {
    return routes.map(route => (
      <Route
        key={route.path}
        path={route.path}
        element={
          route.meta?.permissions ? (
            <PermissionButton permissions={route.meta.permissions}>
              {route.element || <Outlet />}
            </PermissionButton>
          ) : (
            route.element || <Outlet />
          )
        }
      >
        {route.children && renderRoutes(route.children)}
      </Route>
    ));
  };

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route
          path="/"
          element={isAuthenticated ? <Layout><Outlet /></Layout> : <Navigate to="/login" replace />}
        >
          {/* 添加一个默认的重定向到首页 */}
          <Route index element={<Navigate to="/dashboard" replace />} />
          {renderRoutes(staticRoutes.concat(dynamicRoutes))}
        </Route>
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
};

export default Router;
